/* eslint-disable @typescript-eslint/no-shadow */
import { Button, Modal, Drawer } from 'antd';
import type { FC } from 'react';
import { useEffect, useState } from 'react';
import removeSrc from '../remove.png';
import Title from '../title';
import classnames from 'classnames';
import './index.less';
import AddLesson from '../add-lesson';
import { useHistory, useModel } from 'umi';
import { uid, calcIndex } from '@/utils';
import moment from 'moment';
import { allGet, allPost } from '@/services/pc';
interface Props {
  dataSource: any[];
  reload: () => void;
  onSave?: (dataSource: any[]) => void;
}
const Index: FC<Props> = ({ dataSource, onSave, reload }) => {
  const [visible, setVisible] = useState(false);
  const [current, setCurrent] = useState<any>(undefined);
  const [defaultDataSource, setDefaultDataSource] = useState<any[]>([]);
  const [chapter, setChapter] = useState<any[]>([]);
  const [singleton, setSingleton] = useState<any[]>([]);
  /**
   * 获取课程id
   */
  const { classid = 0 } = (useHistory().location as any)?.query;

  const init = (dataSource: any) => {
    if (Array.isArray(dataSource)) {
      setChapter(dataSource.filter((item) => !!item.children));
      setSingleton(dataSource.filter((item) => !!!item.children));
      setDefaultDataSource(dataSource);
    }
  };
  // 添加课时到章节
  const addLessonToChapter = async (lids) => {
    const response = await allGet({
      params: {
        version: 'pc1.0',
        mod: 'chapter',
        do: 'addlesson',
        cid: current.cid,
        lids,
      },
    });
    if (response.success) {
      let newDataSource = JSON.parse(JSON.stringify(defaultDataSource))
        .map((item) => (current.cid === item.cid ? { ...item, children: response.data } : item))
        .filter((item) => !item.lid || lids.indexOf(item.lid) === -1);
      newDataSource = calcIndex(newDataSource);
      init(newDataSource);
      setCurrent({ ...current, ...newDataSource.filter(({ cid }) => cid === current.cid)[0] });
    }
    return response.success;
  };
  // 删除课时到章节
  const onRemoveLecturerForChapter = async (chapter, lecturer) => {
    const response = await allGet({
      params: {
        version: 'pc1.0',
        mod: 'chapter',
        do: 'deletelesson',
        cid: chapter.cid,
        lids: [lecturer.lid],
      },
    });
    if (response.success) {
      await reload();
      let newDataSource = JSON.parse(JSON.stringify(defaultDataSource)).map((item) =>
        chapter.cid === item.cid ? { ...item, children: response.data } : item,
      );
      newDataSource = calcIndex(newDataSource);
      setCurrent({ ...current, ...newDataSource.filter(({ cid }) => cid === chapter.cid)[0] });
    }
  };
  // 删除章节
  const onDeleteChapter = async (removeItem) => {
    // todo
    const response = await allGet({
      params: {
        version: 'pc1.0',
        mod: 'chapter',
        do: 'delete',
        cid: removeItem.cid,
      },
    });
    if (response.success) {
      let newDataSource = JSON.parse(JSON.stringify(defaultDataSource)).filter(
        (item) => removeItem.cid !== item.cid,
      );
      newDataSource = calcIndex(newDataSource);
      init(newDataSource);
    }
  };
  // 弹窗保存按钮
  const onOk = () => {
    reload();
    setVisible(false);
    onSave && onSave([...chapter, ...singleton]);
  };
  // 章节名称修改
  const onChapterTitleChange = async (current: any, title) => {
    // console.log(current);
    // return;
    const params = {
      version: 'pc1.0',
      mod: 'chapter',
      do: 'create',
      classid,
      name: title,
      cid: undefined,
    };

    if (current.cid) {
      params.cid = current.cid;
      params.do = 'update';
    }
    const response = await allGet({
      params,
    });
    if (response.success) {
      let newDataSource = JSON.parse(JSON.stringify(defaultDataSource)).map((item) =>
        current[current.cid ? 'cid' : 'addId'] === item[current.cid ? 'cid' : 'addId']
          ? { ...item, ...response.data, title }
          : item,
      );
      newDataSource = calcIndex(newDataSource);
      init(newDataSource);
    }
  };
  // 清空课时
  const onClearAllLecturer = async (current) => {
    // todo 统一保存的话用这个
    const response = await allGet({
      params: {
        version: 'pc1.0',
        mod: 'chapter',
        do: 'deletelesson',
        cid: current.cid,
        clear: 1,
      },
    });
    if (response.success) {
      await reload();
      setCurrent({
        ...current,
        children: [],
      });
    }
  };
  // 新增章节
  const onAddChapter = async () => {
    const addId = `${uid(6)}-${moment().unix()}`;
    const params = {
      version: 'pc1.0',
      mod: 'chapter',
      do: 'create',
      classid,
      name: '',
      cid: undefined,
    };
    const response = await allGet({
      params,
    });
    if (response.success) {
      let newDataSource = [
        ...JSON.parse(JSON.stringify(defaultDataSource)),
        {
          addId,
          children: [],
          ...response.data,
        },
      ];
      newDataSource = calcIndex(newDataSource);
      init(newDataSource);
    }
  };

  useEffect(() => {
    init(calcIndex(dataSource));
  }, [dataSource]);
  return (
    <div>
      <Button type="primary" onClick={() => setVisible(true)}>
        章节管理
      </Button>
      <Modal
        wrapClassName="c-lecturer-chapter-modal-wrap-container"
        title={null}
        width={650}
        visible={visible}
        closable={false}
        maskClosable={false}
        zIndex={1311}
        onCancel={() => {
          reload();
          setVisible(false);
        }}
        onOk={onOk}
      >
        <div className="c-lecturer-chapter-container">
          <div className="c-lecturer-chapter-header">
            <span className="c-lecturer-chapter-left">章节管理</span>
            <span className="c-lecturer-chapter-right">已添加课时</span>
          </div>
          <div className="c-lecturer-chapter-body">
            <div className="c-lecturer-chapter-left">
              {chapter.map((item, index) => (
                <div
                  key={item.cid || item.id || item.addId}
                  onClick={() => setCurrent({ ...item, indexNumber: index + 1 })}
                  className={classnames('c-lecturer-chapter-item', {
                    'c-lecturer-chapter-item-active': item.cid
                      ? item.cid === current?.cid
                      : item.addId === current?.addId,
                  })}
                >
                  <div className="c-lecturer-chapter-item-head">
                    <span>
                      章节：<span className="text-yellow">{index + 1}</span>
                    </span>
                    <img
                      onClick={(evt) => {
                        evt.stopPropagation();
                        onDeleteChapter(item);
                      }}
                      src={removeSrc}
                      alt=""
                    />
                  </div>
                  <Title
                    onChange={(value) => onChapterTitleChange(item, value)}
                    value={item?.name}
                  />
                </div>
              ))}
              <Button onClick={onAddChapter} type="primary">
                +新建章节
              </Button>
            </div>
            <div className="c-lecturer-chapter-right">
              {current && (
                <>
                  <div className="c-lecturer-chapter-right-header">
                    <span>章节：{current.indexNumber}</span>
                    <a onClick={() => onClearAllLecturer(current)}>清空</a>
                  </div>
                  <div className="c-lecturer-chapter-card-container">
                    {Array.isArray(current.children) &&
                      current.children?.map((item) => (
                        <span className="c-lecturer-chapter-card" key={item.index}>
                          <span>课时: {item.index}</span>
                          <span
                            onClick={() => onRemoveLecturerForChapter(current, item)}
                            className="c-lecturer-chapter-card-close"
                          >
                            X
                          </span>
                        </span>
                      ))}
                    {/* <span className="c-lecturer-chapter-card c-lecturer-chapter-card-add">
                      <span>+添加课时</span>
                    </span> */}
                    <AddLesson
                      chapterIndex={current?.indexNumber}
                      data={singleton}
                      onSubmit={addLessonToChapter}
                    />
                  </div>
                </>
              )}
            </div>
          </div>
        </div>
      </Modal>
    </div>
  );
};
export default Index;
